<?php
/**
 * Created by PhpStorm.
 * User: whwyy
 * Date: 2018/11/8 0008
 * Time: 19:18
 */

namespace BeReborn\Service\Common;


use BeReborn\Core\JSON;
use BeReborn\Error\Logger;
use BeReborn\Http\Context;
use Exception;
use Swoole\Server;

/**
 * Class ServerReceive
 * @package BeReborn\Server
 */
class ServerReceive extends Port
{
	/**
	 * @param Server $server
	 * @param int $fd
	 * @param int $reactor_id
	 * @param string $data
	 * @return mixed
	 * @throws Exception
	 */
	public function onReceive(Server $server, int $fd, int $reactor_id, string $data)
	{
		try {
			if (!is_array($data = unserialize($data))) {
				throw new Exception('Data parsing failed.', 601);
			}

			$array = $server->getClientInfo($fd, $reactor_id);
			if (!isset($data['body'])) $data['body'] = [];

			$this->newRequestInstance($data, $fd, $array);

			$routerData = router()->runHandler();
			if (!is_string($routerData)) {
				$routerData = JSON::encode($routerData);
			}
			return $server->send($fd, $routerData);
		} catch (\Throwable $exception) {
			$json = JSON::to($exception->getCode(), $exception->getMessage());
			return $server->send($fd, $json);
		} finally {
			fire(ServerRequest::AFTER_REQUEST);
			Logger::insert();
		}
	}

}
